<template>
  <div class="book-tree">
    <el-tree
      :data="treeData"
      ref="treeBj"
      :load="loadNode"
      v-loading="loading"
      lazy
      :props="defaultProps"
      :highlight-current="true"
      node-key="nodeId"
      :expand-on-click-node="false"
    >
      <!-- 自定义节点模板 -->
      <span
        class="custom-tree-node"
        slot-scope="{ node, data }"
        @dblclick="headerDbClick(data)"
        @click.stop="onNodeClick(data, node, node.level)"
      >
        <!--已读和未读-->
        <span class="has_new" v-show="data.has_new"></span>
        <!-- 展开/收起按钮(默认图标) -->
        <span
          v-if="node.isLeaf"
          style="width: 20px; display: inline-block"
        ></span>

        <i
          v-if="node.level == 1"
          class="el-icon-folder-opened arrow-icon"
          :class="{ 'is-leaf': node.isLeaf }"
          @click.stop="toggleExpand(node)"
        ></i>
        <i
          v-if="node.level == 2"
          class="el-icon-document arrow-icon"
          @click.stop="toggleExpand(node)"
        ></i>
        <!-- 节点文本 -->

        <span class="node-label" v-if="!data.isEdit">
          {{ data.label }}
        </span>
        <input
          v-else
          :ref="data.id"
          placeholder="请输入内容"
          v-model="currentName"
          @blur="($event) => handleInputBlur($event, data)"
        />

        <!--        &lt;!&ndash; 右侧 ... 下拉菜单 &ndash;&gt;-->
        <!--        <el-dropdown @command="onDropdownCommand($event, data)">-->
        <!--          <span class="dropdown-trigger">-->
        <!--            <i class="el-icon-more" />-->
        <!--          </span>-->
        <!--          <el-dropdown-menu slot="dropdown">-->

        <!--          </el-dropdown-menu>-->
        <!--        </el-dropdown>-->
      </span>
    </el-tree>
  </div>
</template>

<script>
import {
  deleteVolume,
  getVolumeDetail,
  getVolumeList,
  updateVolumeTitle,
  volumeUpdate,
} from "@/api/volumes";
import {
  chapterUpdate,
  createChapter,
  deleteChapter,
  editChapterTitle,
  getChapterContent,
  getChapterList,
} from "@/api/chapter";
import {
  createVersions,
  deleteVersions,
  editVersionsTitle,
  getVersionsList,
} from "@/api/versions";
import {
  getArchElements,
  getArchMaster,
  getArchStages,
  getArchSubsets,
} from "@/api/arch";

export default {
  name: "BookTree",

  data() {
    return {
      time: 200,
      timeOut: null,
      loading: "",
      currentName: "",
      creation_id: "",
      treeData: [],
      expandIds: [],
      defaultProps: {
        children: "children",
        label: "name",
      },
    };
  },
  mounted() {
    this.creation_id = this.$route.params.id;
    this.getVolumeListFun();
  },
  beforeDestroy() {
    window.removeEventListener("resize", this.handleResize);
  },

  methods: {
    saveJuanTile(id, name) {
      updateVolumeTitle(id, name).then((res) => {
        console.log(res);
        this.$modal.msgSuccess("名称修改成功");
        // this.currentDataObj=res.volume
        // this.currentType='1'
      });
    },
    saveZhangTitle(id, name) {
      editChapterTitle(id, name).then((res) => {
        console.log(res);
        this.$modal.msgSuccess("名称修改成功");
      });
    },
    saveBanBenTitle(id, name) {
      editVersionsTitle(id, name).then((res) => {
        console.log(res);
        this.$modal.msgSuccess("名称修改成功");
      });
    },
    headerDbClick(data) {
      clearTimeout(this.timeOut);
      console.log("双击节点", data);
      this.currentName = data.label;
      this.$set(data, "isEdit", true);
      this.$nextTick(() => {
        this.$refs[data.id] && this.$refs[data.id].focus(); // 获取输入框，自动获取焦点
      });
    },
    handleInputBlur(event, data) {
      console.log(event.target.value);
      const inputName = event.target.value.trim();
      if (inputName === "") {
        this.$message({
          type: "warning",
          message: "名称不能为空,请重新输入",
        });
        this.$set(data, "isEdit", false); // 让文本span标签显示，输入框隐藏
      } else if (inputName === data.label) {
        this.$set(data, "isEdit", false);
      } else {
        this.$set(data, "isEdit", false);
        data.label = inputName;
        if (data.level == 1) {
          this.saveJuanTile(data.id, inputName);
        }
        if (data.level == 2) {
          this.saveZhangTitle(data.id, inputName);
        }
        if (data.level == 3) {
          this.saveBanBenTitle(data.id, inputName);
        }
      }
      this.currentName = "";
    },
    refreshTreeNode(parentID) {
      var id = parentID ? parentID : this.parentID;
      if (id && id !== "0") {
        var node = this.$refs.treeBj.getNode(id);
        node.loaded = false;
        node.expand();
      } else {
        this.getVolumeListFun();
      }
    },
    addBb(node) {
      createVersions({
        chap_id: Number(node.id),
      }).then((res) => {
        this.refreshTreeNode(node.nodeId);
        console.log(res);
      });
    },
    addZ(node) {
      createChapter({
        volume_id: Number(node.id),
      }).then((res) => {
        this.refreshTreeNode(node.nodeId);
        console.log(res);
      });
    },
    //14.获取节点数据
    //树渲染完成后自动加载一次。
    async loadNode(node, resolve) {
      // 懒加载
      if (node.level === 0) {
        return resolve([]);
      } else if (node.level === 1) {
        return resolve(await this.getArchSubsets(node.data.id, node.data));
      } else if (node.level === 2) {
        console.log(node);
        return resolve(await this.getArchMaster(node.data.id, node.data));
      } else {
        return resolve([]); // 防止该节点没有子节点时一直转圈的问题出现
      }
    },
    async getVolumeListFun() {
      var that = this;
      this.loading = true;
      var res = await getArchStages({
        creation_id: Number(this.$route.params.id),
      });
      var volume = res;
      var lastId = "";
      volume.forEach((item, index) => {
        // 节点需要构建为 tree 的结构
        item.label = item.title;
        item.nodeId = "stage" + item.id;
        item.leaf = false;
        item.level = 1;
        lastId = "stage" + item.id;
      });
      this.loading = false;
      this.treeData = volume;

      if (lastId) {
        setTimeout(function () {
          that.refreshTreeNode(lastId, true);
        }, 500);
      }
      // return volume
    },
    async getArchMaster(id, data) {
      this.loading = true;
      var res = await getArchElements({ subset_id: Number(id) });
      var versions = [];
      if (res && res.length > 0) {
        versions = res;
        versions.forEach((item, index) => {
          // 节点需要构建为 tree 的结构
          item.label = item.title;
          item.pId = "subset" + id;
          item.subset_id = id;
          item.nodeId = "master" + item.keyword;
          item.leaf = true;
          item.level = 3;
          item.id = item.keyword;
        });
      }

      this.loading = false;

      return versions;
    },
    async getArchSubsets(id) {
      this.loading = true;
      var that = this;
      var res = await getArchSubsets({ stage_id: Number(id) });
      var chapter = [];
      var lastItem = {};
      if (res && res.length > 0) {
        chapter = res;
        chapter.forEach((item, index) => {
          // 节点需要构建为 tree 的结构
          item.label = item.title;
          item.pId = "stage" + id;
          item.nodeId = "subset" + item.id;
          item.leaf = false;
          item.level = 2;
          lastItem = item;
        });
      }
      this.$refs.treeBj.setCurrentKey(lastItem.nodeId); // 'id'是你数据中唯一标识的字段
      this.$emit("node-click", lastItem);
      // setTimeout(function (){
      //   that.refreshTreeNode(lastId,true)
      // },500)

      this.loading = false;
      return chapter;
    },
    //16.树点击事件
    treeClick(data, node) {
      //console.log('data', data, node);
      this.nodeId = node.data.value;
      this.formData.FDepartID = data.value;
      this.upsearch();
    },

    // 切换展开/收起
    toggleExpand(node) {
      if (!node.isLeaf) {
        node.expanded = !node.expanded;
      }
    },
    onNodeClick(data, node, level) {
      clearTimeout(this.timeOut);
      var that = this;
      this.timeOut = setTimeout(function () {
        if (level != 1) {
          that.$refs.treeBj.setCurrentKey(data.nodeId); // 'id'是你数据中唯一标识的字段
          that.$emit("node-click", data);
        } else {
          if (node.expanded) {
            node.expanded = false;
          } else {
            console.log(node);
            node.loaded = false;
            node.expand();
          }
        }
      }, 200);
    },
    // 下拉菜单点击
    onDropdownCommand(command, nodeData) {
      // 将命令和节点信息抛给父组件
      this.$message(`对节点【${nodeData.label}】执行[${command}]操作(示例)`);
      if (command === "addz") {
        // 例如重命名
        this.addZ(nodeData);
      }
      if (command === "addbb") {
        // 例如重命名
        this.addBb(nodeData);
      }
      if (command === "rename") {
        // 例如重命名
        this.$prompt("请输入新名称", "重命名", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
        })
          .then(({ value }) => {
            nodeData.label = value;
          })
          .catch(() => {});
      } else if (command === "delete1") {
        // 例如删除
        this.$confirm("确认删除该卷吗？", "提示", { type: "warning" })
          .then(() => {
            // 在treeData里把它移除
            deleteVolume(nodeData.id).then((res) => {
              this.refreshTreeNode(nodeData.nodeId);
              this.$message.success("删除成功");
            });
          })
          .catch(() => {});
      } else if (command === "delete2") {
        // 例如删除
        this.$confirm("确认删除该章节吗？", "提示", { type: "warning" })
          .then(() => {
            // 在treeData里把它移除
            console.log(nodeData);
            deleteChapter(nodeData.id).then((res) => {
              this.refreshTreeNode(nodeData.pId);
              this.$message.success("删除成功");
              // 调用副节点刷新
            });
          })
          .catch(() => {});
      } else if (command === "delete3") {
        // 例如删除
        this.$confirm("确认删除该版本吗？", "提示", { type: "warning" })
          .then(() => {
            // 在treeData里把它移除
            console.log(nodeData);
            deleteVersions(nodeData.id).then((res) => {
              this.refreshTreeNode(nodeData.pId);
              this.$message.success("删除成功");
              // 调用副节点刷新
            });
          })
          .catch(() => {});
      }
    },
  },
};
</script>

<style scoped lang="scss">
.book-tree {
  ::v-deep
    .el-tree--highlight-current
    .el-tree-node.is-current
    > .el-tree-node__content {
    background: linear-gradient(
      90deg,
      rgba(22, 93, 235, 0.12) 0%,
      rgba(22, 93, 235, 0.04) 100%
    ) !important;
    .el-dropdown {
      display: block;
    }
  }
  .el-tree {
    background-color: transparent; // 去掉默认白色背景
    ::v-deep .el-tree-node__content {
      position: relative;
      height: 30px;
    }
    ::v-deep .el-tree-node__content:hover {
      background: linear-gradient(
        90deg,
        rgba(22, 93, 235, 0.12) 0%,
        rgba(22, 93, 235, 0.04) 100%
      ) !important;
      .el-dropdown {
        display: block;
      }
    }
    ::v-deep .el-icon-caret-right {
      margin-left: 23px;
    }
    ::v-deep .el-tree-node__expand-icon.is-leaf {
      margin-left: 0 !important;
    }
    .custom-tree-node {
      display: block;
      white-space: nowrap; /* 不换行 */
      overflow: hidden; /* 隐藏超出的内容 */
      text-overflow: ellipsis; /* 用省略号表示被隐藏的部分 */
      padding-right: 10px;
      .has_new {
        display: inline-block;
        height: 6px;
        width: 6px;
        border-radius: 50%;
        background: #4388ff;
        position: absolute;
        left: 20px;
        top: 11px;
      }

      .arrow-icon {
        cursor: pointer;
        margin-right: 4px;
        font-size: 14px;
        &.is-leaf {
          visibility: hidden; // 叶子节点不显示箭头
        }
      }
      .node-label {
        margin-right: 6px;
        cursor: pointer;
      }
      ::v-deep .el-dropdown {
        position: absolute;
        right: 14px;
        display: none;
        top: 0;
      }

      .dropdown-trigger {
        cursor: pointer;
        margin-left: auto;
        padding: 0 4px;
      }
    }
  }
}
</style>
<style></style>
